package com.newsee.remote.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.dto.contract.ContractDTO;
import com.newsee.remote.common.dto.contract.ContractReqItemDTO;
import com.newsee.remote.common.dto.contract.ContractReqItemInfoDTO;
import com.newsee.remote.common.dto.costcenter.CostReqBaseInfoDTO;
import com.newsee.remote.common.enumeration.SrmRspStatusCodeEnum;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.common.vo.costcenter.CostCenterVO;
import com.newsee.remote.common.vo.supplier.EResponseVO;
import com.newsee.remote.common.vo.supplier.MessageVO;
import com.newsee.remote.common.vo.supplier.RspBaseInfoVO;
import com.newsee.remote.common.vo.supplier.RspItemVO;
import com.newsee.remote.common.database.entity.ShContract;
import com.newsee.remote.common.database.entity.ShContractInfo;
import com.newsee.remote.common.database.mapper.ShContractMapper;
import com.newsee.remote.contract.service.IShContractInfoService;
import com.newsee.remote.contract.service.IShContractService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-12-16
 */
@Service
@Slf4j
public class ShContractServiceImpl extends ServiceImpl<ShContractMapper, ShContract> implements IShContractService {

    private final IShContractInfoService iShContractInfoService;

    public ShContractServiceImpl(IShContractInfoService iShContractInfoService) {
        this.iShContractInfoService = iShContractInfoService;
    }

    @Override
    public CostCenterVO acceptContract(ContractDTO dto) {
        CostCenterVO vo = new CostCenterVO();

        try {
            //srm提供的供应商报文
            List<ContractReqItemDTO> heads = dto.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (ContractReqItemDTO head : heads) {
                //唯一标识
                String contractId = head.getCONTRACT_ID();
                ShContract shContract = getOne(new QueryWrapper<ShContract>().eq("CONTRACT_ID", contractId));

                //新增
                if (null == shContract) {
                    shContract = new ShContract();
                    shContract.setCreateTime(LocalDateTime.now());
                } else {
                    shContract.setUpdateTime(LocalDateTime.now());
                }
                buildContract(head, shContract);
                saveOrUpdate(shContract);
            }
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收合同主数据出错：" + e.getMessage());
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;
    }

    /**
     * 实体装换
     *
     * @param head       源数据
     * @param shContract 目标
     */
    private void buildContract(ContractReqItemDTO head, ShContract shContract) {
        shContract.setContractId(head.getCONTRACT_ID());
        shContract.setContPrtid(head.getCONT_PRTID());
        shContract.setContShort(head.getCONT_SHORT());
        shContract.setBukrs(head.getBUKRS());
        shContract.setContTyp(head.getCONT_TYP());
        shContract.setPartyA(head.getPARTY_A());
        shContract.setPartyB(head.getPARTY_B());
        shContract.setPartyC(head.getPARTY_C());
        shContract.setContAmt(head.getCONT_AMT());
        shContract.setContZxzjYb(head.getCONT_ZXZJ_YB());
        shContract.setIsSpinv(head.getIS_SPINV());
        shContract.setContAttn(head.getCONT_ATTN());
        shContract.setContHtfzr(head.getCONT_HTFZR());
        shContract.setSrelContfid(head.getSREL_CONTFID());
        shContract.setPassDat(head.getPASS_DAT());
        shContract.setContApprSta(head.getCONT_APPR_STA());
        shContract.setContSta(head.getCONT_STA());

        List<ContractReqItemInfoDTO> infos = head.getREQ_ITEM_INFO();
        if (CollectionUtils.isNotEmpty(infos)) {
            for (ContractReqItemInfoDTO info : infos) {
                //唯一标识
                String contractId = info.getCONTRACT_ID();
                String seqnr = info.getSEQNR();
                if (StringUtils.isNotBlank(contractId) && StringUtils.isNotBlank(seqnr)) {
                    ShContractInfo shContractInfo = iShContractInfoService.getOne(new QueryWrapper<ShContractInfo>().eq("CONTRACT_ID", contractId).eq("SEQNR",seqnr));

                    //新增
                    if (null == shContractInfo) {
                        shContractInfo = new ShContractInfo();
                        shContractInfo.setCreateTime(LocalDateTime.now());
                    } else {
                        shContractInfo.setUpdateTime(LocalDateTime.now());
                    }
                    shContractInfo.setContractId(info.getCONTRACT_ID());
                    shContractInfo.setSeqnr(info.getSEQNR());
                    shContractInfo.setByear(info.getBYEAR());
                    shContractInfo.setBrdeptno(info.getBRDEPTNO());
                    shContractInfo.setBracctno(info.getBRACCTNO());
                    shContractInfo.setAmount(info.getAMOUNT());
                    shContractInfo.setNtaxAmt(info.getNTAX_AMT());
                    shContractInfo.setTaxAmt(info.getTAX_AMT());
                    shContractInfo.setTaxRt(info.getTAX_RT());
                    shContractInfo.setHsbm(info.getHSBM());
                    iShContractInfoService.saveOrUpdate(shContractInfo);
                } else {
                    log.info("合同主数据唯一标识为空：contractId{}", contractId);
                }

            }
        }
    }


    /**
     * 生成响应报文基础信息名称
     *
     * @param reqBaseinfo 请求
     * @param vo          返回
     */
    private void generatorRspBaseInfo(CostReqBaseInfoDTO reqBaseinfo, CostCenterVO vo, String rspStatsCode) {

        //-------封装返回对象--------
        //响应报文根节点名称
        EResponseVO eResponseVO = new EResponseVO();
        vo.setE_RESPONSE(eResponseVO);

        //响应报文基础信息名称
        RspBaseInfoVO rspBaseInfoVO = new RspBaseInfoVO();
        eResponseVO.setRSP_BASEINFO(rspBaseInfoVO);
        //接收系统返回消息，产生的 TRACE_ID，消息的唯一标识
        rspBaseInfoVO.setRSP_TRACE_ID(UUID.randomUUID().toString().replace("-", ""));
        //响应请求 TRACE_ID
        rspBaseInfoVO.setRSP_REQ_TRACEID(reqBaseinfo.getREQ_TRACE_ID());
        //报文发送时间，14位数字
        rspBaseInfoVO.setRSP_SEND_TIME(Long.valueOf(DateUtils.format(new Date(), DateUtils.DATE_PATTERN_FULL)));
        //发送方系统标识
        rspBaseInfoVO.setRSP_SRC_SYS(reqBaseinfo.getREQ_SRC_SYS());
        //接收方系统标识:
        rspBaseInfoVO.setRSP_TAR_SYS("BS-WY-RFWZ");
        //PO 或 ESB 上定义的SI名称，由PO或ESB/顾问提供
        rspBaseInfoVO.setRSP_SERVER_NAME(reqBaseinfo.getREQ_SERVER_NAME());
        //业务系统流水号或业务唯一编号，从请求报文中获取
        rspBaseInfoVO.setRSP_BSN_ID(reqBaseinfo.getREQ_BSN_ID());
        //接口处理状态代码
        rspBaseInfoVO.setRSP_STATUS_CODE(rspStatsCode);

        //给srm返回的信息
        MessageVO messageVO = new MessageVO();
        RspItemVO rspItemVO = new RspItemVO();
        eResponseVO.setMESSAGE(messageVO);
        messageVO.setRSP_ITEM(rspItemVO);
        rspItemVO.setRSP_STATUS_CODE(rspStatsCode);
        rspItemVO.setRSP_STATUS_MSG(SrmRspStatusCodeEnum.getTextByCode(rspStatsCode));
    }
}
